package ar.com.photo_admin.activity;

import java.util.ArrayList;
import java.util.List;

import jim.h.common.android.lib.zxing.config.ZXingLibConfig;
import jim.h.common.android.lib.zxing.integrator.IntentIntegrator;
import jim.h.common.android.lib.zxing.integrator.IntentResult;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import ar.com.photo_admin.Constants;
import ar.com.photo_admin.R;
import ar.com.photo_admin.services.ServiceLayer;
import ar.com.photo_admin.services.ServiceLayerImpl.TokenOperationResponse;
import ar.com.photo_admin.services.ServiceLayerImpl.TokenOperationResponse.TokenOperationCode;
import ar.com.photo_admin.services.Services;

public class MainMenuActivity extends ListActivity {

	private List<MainMenuListItem> items = new ArrayList<MainMenuListItem>();
	private ArrayAdapter<MainMenuListItem> adapter;
	
	private MainMenuListItem selectedItem;
	
	private ServiceLayer webService;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_menu_list);
		
		webService = Services.createServiceLayer(this);
		
		MainMenuListItem myEvents = new MainMenuListItem(R.drawable.ic_launcher, R.string.my_events, new MainMenuListItemCommand() {
			
			@Override
			protected void request() {
				Intent intent = new Intent(MainMenuActivity.this, EventListActivity.class);
				startActivity(intent);	
			}

			@Override
			protected void response(int requestCode, int resultCode, Intent data) {				
			}
		}, Constants.MY_EVENTS_CODE);
		
		MainMenuListItem addEvents = new MainMenuListItem(R.drawable.ic_qr, R.string.add_events, new MainMenuListItemCommand() {
			
			@Override
			protected void request() {
				ZXingLibConfig zxingLibConfig = new ZXingLibConfig();
		        zxingLibConfig.useFrontLight = true;
		        
		        IntentIntegrator.initiateScan(MainMenuActivity.this, zxingLibConfig);
			}

			@Override
			protected void response(int requestCode, int resultCode, Intent data) {				
				new AddTokenTask(requestCode, resultCode, data).execute();
			}
		}, Constants.ADD_TOKEN_CODE);
		
		MainMenuListItem config = new MainMenuListItem(R.drawable.ic_my_configuration, R.string.config, new MainMenuListItemCommand() {
			
			@Override
			protected void request() {
				Intent intent = new Intent(MainMenuActivity.this, SettingsActivity.class);
				startActivity(intent);
			}

			@Override
			protected void response(int requestCode, int resultCode, Intent data) {				
			}
		}, Constants.CONFIG_CODE);
		
		items.add(myEvents);
		items.add(addEvents);
		items.add(config);
		
		this.adapter = (new ArrayAdapter<MainMenuListItem>(this,
				R.layout.item_list_image, items) {
			
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				
				View row = convertView;

				if (row == null) {
					LayoutInflater inflater = getLayoutInflater();
					row = inflater.inflate(R.layout.item_list_image, parent, false);
				}
				
				final MainMenuListItem item = getItem(position);
				
				TextView name = (TextView) row.findViewById(R.id.text);
				name.setText(item.text);
				 
				ImageView image = (ImageView) row.findViewById(R.id.image);
				image.setImageResource(item.drawableId);
			    
				return row;
			}
		});
		
		setListAdapter(adapter);
		
		if (savedInstanceState != null) {
			Integer itemCode = savedInstanceState.getInt(Constants.ITEM);
			
			if (Constants.ADD_TOKEN_CODE.equals(itemCode))
				selectedItem = addEvents;
		}
			
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		
		selectedItem = adapter.getItem(position);
		Toast.makeText(this, selectedItem.text, Toast.LENGTH_SHORT).show();
		
		selectedItem.command.request();
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        selectedItem.command.response(requestCode, resultCode, data);
    }
	
	private class MainMenuListItem {
		
		public Integer drawableId;
		public String text;
		public MainMenuListItemCommand command;
		public Integer code;
		
		public MainMenuListItem(Integer drawableId, Integer textId,
				MainMenuListItemCommand command, Integer code) {
			
			this.drawableId = drawableId;
			this.text = getResources().getString(textId);
			this.command = command;
			this.code = code;
		}
	}
	
	private abstract class MainMenuListItemCommand {
		protected abstract void request();
		protected abstract void response(int requestCode, int resultCode, Intent data);
	}
	
	private class AddTokenTask extends AsyncTask<Void, Void, TokenOperationResponse> {

		private ProgressDialog dialog = null;
		
		int requestCode;
		int resultCode;
		Intent data;
		
		public AddTokenTask(int requestCode, int resultCode, Intent data) {
			this.requestCode = requestCode;
			this.resultCode = resultCode;
			this.data = data;
		}

		@Override
		protected void onPreExecute() {
		
			dialog = new ProgressDialog(MainMenuActivity.this);
			dialog.setTitle(getString(R.string.loading));
			dialog.setMessage(getString(R.string.processing_token));
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			dialog.show();
		}
		
		@Override
		protected TokenOperationResponse doInBackground(Void... params) {
			
			switch (requestCode) {
            case IntentIntegrator.REQUEST_CODE:
	                IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode,
	                        resultCode, data);
	                
	                if (scanResult == null) {
	                    return null;
	                }
	                
	                final String result = scanResult.getContents();
	                
	                if (result != null) {
	                	return webService.addToken(result);
	                }
	                break;
	            default:
			}				
			
			return null;
		}
		
		@Override
		protected void onPostExecute(TokenOperationResponse result) {

			this.dialog.dismiss();
			
			if (result != null) {
				
				Toast.makeText(MainMenuActivity.this, result.message, Toast.LENGTH_SHORT).show();

				if (result.code == TokenOperationCode.ADDED) {
					Intent intent = new Intent(MainMenuActivity.this, EventListActivity.class);
					startActivity(intent);	
				}				
			}
		}
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(Constants.ITEM, selectedItem.code);
	}
}